<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="3%"
    width="30%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      :label-width="$i18n.locale === 'en-US' ? '100px' : '100px'"
      :disabled="disabled"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="开抢时间" prop="robTime">
            <el-time-picker
              v-model="dataForm.robTime"
              value-format="HH:mm"
              :default-value="dataForm.robTime"
              format="HH:mm"
              placeholder="开抢时间"
              style="width: 100%"
              :disabled="true"
            >
            </el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="游玩日期" prop="playDate">
            <el-date-picker
              v-model="dataForm.playDate"
              type="date"
              :default-value="dataForm.playDate"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width: 100%"
              :disabled="true"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="游玩时间" prop="playTime">
            <el-select
              v-model="dataForm.playTime"
              placeholder="请选择游玩时间"
              clearable
              style="width: 100%"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="(item, index) in times"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="选择商品" prop="goodsId">
            <el-select
              v-model="dataForm.goodsId"
              placeholder="请选择商品"
              clearable
              style="width: 100%"
            >
              <el-option
                :label="item.goodsName"
                :value="item.id"
                v-for="(item, index) in goodsData"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="数量" prop="initNum">
            <el-select
              v-model="dataForm.initNum"
              placeholder="请选择数量"
              clearable
              style="width: 100%"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="(item, index) in nums"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="优惠价" prop="discountPrice">
            <el-input
              type="number"
              v-model="dataForm.discountPrice"
              placeholder="优惠价"
              min="0"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上下架" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer" v-if="!disabled">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import editorVue from "@/components/editor";
export default {
  data() {
    return {
      disabled: false,
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      url2: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/tinymce/upload?access_token=${Cookies.get("access_token")}`,
      fileList: [],
      Scenicspotdata: [],
      scenicOptions: [],
      times: [], //运营时间
      replaceList: [],
      replaceList2: [],
      fileList2: [], //轮播图
      fileList1: [], //封面图
      visible: false,
      dialogVisible1: false,
      dialogImageUrl1: "",
      dialogImageUrl2: "",
      dialogVisible2: false,
      activeName: "first",
      size: "30%",
      title: "",
      nums: [],
      goodsData: [],
      times: [
        "05:00",
        "06:00",
        "07:00",
        "08:00",
        "09:00",
        "10:00",
        "11:00",
        "12:00",
        "13:00",
        "14:00",
        "15:00",
        "16:00",
      ],
      dataForm: {
        goodsId: "",
        id: "",
        boardSite: "",
        initNum: null,
        residueNum: null,
        status: 1,
        buyGuide: "",
        playDate: "",
        playTime: "",
        clusteringNum: "",
        discountPrice: "",
        featureLabels: "",
        goodsName: "",
        goodsType: "",
        merchantId:
          this.$store.state.user.MerchantId ||
          localStorage.getItem("MerchantId"),
        normalPrice: "",
        playArea: "",
        playLength: "",
        publishType: 0,
        robTime: "20:00",
        seatNum: "",
        tripLights: "",
        workWay: "",
      },
    };
  },
  props: ["goodsType"],
  created() {},
  components: {
    editorVue,
  },
  watch: {
    "dataForm.playTime"(newval, oldval) {
      if (newval != oldval) {
        this.getNum();
      }
    },
  },
  computed: {
    dataRule() {
      return {
        goodsName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        initNum: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        goodsId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        boatType: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        clusteringNum: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        seatNum: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        normalPrice: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        featureLabels: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        playArea: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        workWay: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        boardSite: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        playDate: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        playTime: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        discountPrice: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        initNum: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        robTime: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        // tripLights: [
        //   {
        //     required: true,
        //     message: this.$t("validate.required"),
        //     trigger: "blur",
        //   }
        // ]
      };
    },
  },
  methods: {
    init() {
      this.visible = true;
      this.getGoodsData();
      this.dataForm.playDate = this.GetDateStr(2);
      this.$nextTick(() => {
        this.nums = [];
        this.$refs["dataForm"].resetFields();
      });
    },
    //获取库存
    getNum(initNum) {
      if (!this.dataForm.playTime) {
        return false;
      }
      this.nums = [];
      this.dataForm.initNum = "";
      this.$http
        .post("scenic/goods/queryStockAmount", {
          merchantId: this.dataForm.merchantId,
          playDate: this.dataForm.playDate,
          playTime: this.dataForm.playTime,
        })
        .then((res) => {
          let data = res.data.data;
          this.setNums(data || 9);
        });
    },
    setNums(num) {
      for (let i = 0; i < num; i++) {
        this.nums.push(i + 1);
      }
    },
    getGoodsData() {
      this.$http
        .get("/scenic/goods/page", {
          params: {
            merchantId: this.dataForm.merchantId,
            limit: 10,
            page: 1,
            goodsType: 2,
          },
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.goodsData = res.data.data.list;
            if (this.dataForm.id) {
              this.getInfo();
            }
          }
        });
    },
    GetDateStr(AddCount) {
      var dd = new Date();
      dd.setDate(dd.getDate() + AddCount); //获取AddDayCount天后的日期
      var y = dd.getFullYear();
      var m = dd.getMonth() + 1; //获取当前月份的日期
      var d = dd.getDate();
      m = m > 9 ? m : "0" + m;
      d = d > 9 ? d : "0" + d;
      return y + "-" + m + "-" + d;
    },
    getInfo() {
      this.$http
        .get("/scenic/goods/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          setTimeout(() => {
            this.dataForm.initNum = res.data.initNum;
          }, 100);
          this.dataForm.goodsId = this.goodsData.filter(
            (item) => item.goodsName == this.dataForm.goodsName
          )[0].id;
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }

          this.dataForm.residueClusteringNum = null;

          let newDataFrom = this.goodsData.filter(
            (item) => item.id == this.dataForm.goodsId
          )[0];
          if (!newDataFrom) {
            return this.$message.error("请选择商品");
          }
          if (!this.dataForm.id) {
            //新增
          } else {
            //编辑暂存特价主键id
            var id = this.dataForm.id;
          }
          let tempDataForm = JSON.parse(JSON.stringify(this.dataForm));
          this.$set(newDataFrom, "goodsId", tempDataForm.goodsId);
          this.dataForm = newDataFrom;
          this.dataForm.initNum = tempDataForm.initNum;
          this.dataForm.discountPrice = tempDataForm.discountPrice;
          this.dataForm.robTime = tempDataForm.robTime;
          this.dataForm.playDate = tempDataForm.playDate;
          this.dataForm.playTime = tempDataForm.playTime;
          this.dataForm.status = tempDataForm.status;
          this.dataForm.goodsType = 1;
          this.dataForm.residueNum = this.dataForm.initNum;
          if (id) {
            this.dataForm.id = id;
          } else {
            this.dataForm.id = "";
          }
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/scenic/goods",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>

<style>
</style><style lang="scss" scoped>
::v-deep.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 336px;
}

// .aui-content .ql-container {
//     height: auto;
// }

.listItem,
.listItem2 {
  display: grid;
  margin-bottom: 10px;
  gap: 0 20px;
  grid-template-columns: 300px 200px 200px 40px;
}

.listItem2 {
  grid-template-columns: 200px 200px auto 40px;
}

::v-deep.avatar-uploader .el-upload {
  border: 0;
}

::v-deep.el-time-spinner__wrapper {
  width: 50% !important;

  &:last-child {
    display: none;
  }
}
</style>
